package com.lz.springboot.mongo;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;

@Component
@EnableApolloConfig({ "Java.mongo" })
@PropertySource(value = "classpath:mongo.properties", ignoreResourceNotFound = true)
public class ApolloConfigMongo {

	private static final Logger LOGGER = LoggerFactory.getLogger(ApolloConfigMongo.class);
	@ApolloConfig("Java.mongo")
	private Config config;

	@Value("${spring.data.mongo.first.database:test}")
	private String databaseFisrt;
	@Value("${spring.data.mongo.first.host:127.0.0.1}")
	private String hostFisrt;
	@Value("${spring.data.mongo.first.port:5672}")
	private Integer portFisrt;
	@Value("${spring.data.mongo.first.username:mongo}")
	private String usernameFisrt;
	@Value("${spring.data.mongo.first.password:mongo}")
	private String passwordFisrt;
	

	@Value("${spring.data.mongo.second.database:test}")
	private String databaseSecond;
	@Value("${spring.data.mongo.second.host:127.0.0.1}")
	private String hostSecond;
	@Value("${spring.data.mongo.second.port:5672}")
	private Integer portSecond;
	@Value("${spring.data.mongo.second.username:mongo}")
	private String usernameSecond;
	@Value("${spring.data.mongo.second.password:mongo}")
	private String passwordSecond;

	@ApolloConfigChangeListener("Java.mongo")
	private void anotherOnChange(ConfigChangeEvent changeEvent) {
		Set<String> configNames = config.getPropertyNames();
		for (String configName : configNames) {
			LOGGER.info("configName=[{}] configValue=[{}]", configName, config.getProperty(configName, ""));
		}
	}

	@Override
	public String toString() {
		return "MongoConfig [databaseFisrt=" + databaseFisrt + ", hostFisrt=" + hostFisrt + ", portFisrt=" + portFisrt
				+ ", usernameFisrt=" + usernameFisrt + ", passwordFisrt=" + passwordFisrt + ", databaseSecond="
				+ databaseSecond + ", hostSecond=" + hostSecond + ", portSecond=" + portSecond + ", usernameSecond="
				+ usernameSecond + ", passwordSecond=" + passwordSecond + "]";
	}
	
}